<template>
  <div class="videoDown">
    <el-row>
      <el-col style="display: flex; align-items: center; margin-bottom: 10px"
        ><div class="border"></div>
        <h3>{{ roomNo }}   <span style="margin-left:20px">{{ downOldName }}</span></h3>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="16">
        <div
          style="
            display: flex;
            align-items: center;
            margin-left: 20px;
            margin-top: 10px;
          "
        >
          <p style="color: #222222; font-size: 18px">期間指定より録画ファイルを検索：</p>
          <div style="
              margin-left: 30px;
              color: #666666;
              font-size: 15px;
              margin-top: 2px;">
            <p>
              ※照会する期間を本日までのうち、最大48時間の範囲で選択してください。
            </p>
            <p>
              ※Toの日付が未入力の場合、照会時点までのファイルが確認できます。
            </p>
          </div>
        </div>
      </el-col>
      <el-col :span="4">
        <video
          id="remoteVideo"
          ref="remoteVideo"
          class="remotevideo hidevideo"
          style="object-fit: fill"
          preload="auto"
          autoplay
          playsinline="true"
          webkit-playsinline="true"
          x5-video-player-type="h5"
          x5-video-player-fullscreen="true"
          x5-video-orientation="portraint"
        ></video>
      </el-col>
    </el-row>
    <el-row class="roomGeneralViewDetail-e height40">
      <el-col :span="12">
        <el-date-picker
          style="width: 98%"
          v-model="timeValueTable"
          :editable="false"
          format="yyyy-MM-dd HH:mm"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          unlink-panels
          :start-placeholder="videoDown.startDate"
          :picker-options="pickerOptions"
          :end-placeholder="videoDown.endDate">
        </el-date-picker>
      </el-col>
      <el-col :span="12">
        <kt-button
          class="btn0 boxShadowButton"
          :label="videoDown.search"
          @click="serachAlarmTable"
        />
        <kt-button
          class="btn0 boxShadowButton"
          label="一括ダウンロード"
          v-if="false"
          @click="DownAllVideo"
        />
      </el-col>
    </el-row>
    <el-table
      ref="tableList"
      :data="tableData"
      style="width: 60%; margin-top: 10px; margin-left: 20px"
      :row-style="tableRowStyle"
      :header-cell-style="tableHeaderColor"
    >
      <el-table-column
        prop="startTime"
        label="開始日時"
        min-width="150"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="endTime"
        label="終了日時"
        min-width="150"
        align="center"
      ></el-table-column>
      <el-table-column
        :label="videoDown.opertion"
        min-width="180"
        align="center"
      >
        <template slot-scope="scope">
          <img
            class="handedness"
            v-if="scope.row.state == 1"
            :src="image.downvideo_download"
            alt
            @click="alarmVideoDownClick(scope.$index, scope.row)"
          />
          <img
            class="handedness"
            v-else-if="scope.row.state == 2"
            :src="image.downvideo_download"
            alt
            @click="alarmVideoDownClick(scope.$index, scope.row)"
          />
          <img class="handedness" v-else :src="image.downvideo_stop" alt />
          <span v-if="scope.row.state == 1">ダウンロード</span>
          <span v-else-if="scope.row.state == 2">ダウンロード済</span>
          <span v-else>自動消去済</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      background
      layout="total,prev, pager, next,jumper"
      :total="total"
      style="margin-top: 20px"
      align="center"
      :current-page="currentPage"
      @current-change="changePage"
    >
    </el-pagination>

    <el-dialog title="ダウンロード" width="30%" :visible.sync="dialogTableVisible">
      <el-table :data="allVideoData" ref="multipleTable" >
        <el-table-column
          type="selection" width="55">
        </el-table-column>
        <el-table-column 
          prop="startTime"
          :label="videoDown.listStartTime"
          min-width="150"
          align="center"></el-table-column>
        <el-table-column prop="endTime"
          :label="videoDown.listEnterTime"
          min-width="150"
          align="center"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button
            class="deleteBtn boxShadowButton" :size="size" @click="clickdownAllVideo">ダウンロード</el-button>
            <el-button class=" boxShadowButton" :size="size" @click="dialogTableVisible = false">キャンセル</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import KtButton from "@/components/KtButton";
import bus from "../../../vuex/eventBus"; //引入eventBus,接收子界面传递的跳转指令,然后在父界面跳转,添加tab
import downvideo_play from "../../../assets/lifeGroupimg/downvideo_play.png";
import downvideo_download from "../../../assets/lifeGroupimg/downvideo_download.png";
import downvideo_stop from "../../../assets/lifeGroupimg/downvideo_stop.png";
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ trickle: false });
export default {
  data() {
    return {
      videoDown: this.$t("m.videoDown"), //引入 lang 里面的字符串资源,
      size: "mini", //按钮的尺寸
      loading: false,
      acceptLanguage: "ja_JP", //数据请求传参需要传的语言  ja_JP----日文
      timeValueTable: null, //报警列表的查询,时间
      pickerOptions: {
        onPick: time => {
          if (time.minDate && !time.maxDate) {
            this.timeOptionRange = time.minDate;
          }
          if (time.maxDate) {
            this.timeOptionRange = null;
          }
        },
        disabledDate: (time) => {
          // 如何选择了一个日期
          const one = 6 * 24 * 600 * 2 * 1000;//这里如果乘以2相当于限制3天以内的 
          // 如果没有选择日期，就要限制不能选择今天及以后
          return time.getTime() >  this.getDayStartOrEnd(new Date(),"end") || time.getTime()< (this.getDayStartOrEnd(new Date(),"start")-one);
          
        },
      },
      image: {
        downvideo_play,
        downvideo_download,
        downvideo_stop,
      },
      tableData: [],
      mulitStartDown:false, //是否处于下载中
      multipIndex:0,
      allVideoData:[],
      roomId: "",
      oldmanId: "",
      roomNo: "",
      id:"",
      downOldName:"",
      file_data_len:0, //文件大小
      recv_data_len:0,//下载文件大小
      RTCPeerConnectionCreated:false,
      dialogTableVisible:false,
      timer:null,
      videoSrc:'',//播放的文件路径
      startTime: "",
      endTime: "",
      total: 0,
      pageNum: 1,
      pageSize: 10,
      currentPage: 1,
      firstPage: "", //第一页
      lastPage: "", //最后一页
      //webrtc
      cameraInfo: "",
      wsuri: "",
      IsReconnect: false,
      timeout: 2000,
      timedelay: 0,
      serverTimeoutObj: null,
      IceCandidate: new Array(),
      onnectmode: "live",
      connectsource: "MainStream",
      configuration: {
        iceServers: [{ urls: ["stun:stun.l.google.com:19302?transport=udp"] }],
      },
    };
  },
  components: {
    KtButton,
  },
  methods: {
    // 获取当天0点或23:59:59
    getDayStartOrEnd(time,type = "start"){//end  返回毫秒数
            if(type == "start"){
                return new Date(time).setHours(0,0,0,0);//hourse、min、sec、millisec
            }else{
                return new Date(time).setHours(23,59,59,999);
            }
    },
    serachAlarmTable() {
      if (this.timeValueTable != null) {
        this.startTime = this.timeValueTable[0];
        this.endTime = this.timeValueTable[1];
      } else {
        this.startTime = "";
        this.endTime = "";
      }
      this.getList();
    },
    DownAllVideo(){
      let param = {
        pageNum: 1,
        pageSize: 9999,
        roomId: this.roomId,
        startTime: this.startTime,
        endTime: this.endTime,
      };
      this.$postJson(
        "dmc/cameraRecordVideo/queryListWithPage",
        param,
        this.acceptLanguage
      ).then((res) => {
        this.allVideoData = [];
        res.result.list.forEach(item =>{
          if(item.state == 1){
            this.allVideoData.push(item);
          }
        })
        this.dialogTableVisible = true;
      });
    },
    clickdownAllVideo(){
      let arr = this.$refs.multipleTable.selection;
      console.log('arr', arr);
      this.checkItemList = arr;
      this.multipIndex = 0;
      this.mulitStartDown = false;
      let size = arr.length;
      console.log('size', size);
      var that = this;
      this.dialogTableVisible = false;
      if(this.timer!=null){
        clearInterval(timer);
      }
      this.timer = setInterval(function() {
        if(that.multipIndex < size && !that.mulitStartDown){
          that.mulitStartDown = true;
          console.log('==========>>>=========while1 >> ===' + that.multipIndex);
          let param = {
            id: that.checkItemList[that.multipIndex].id,
          };
          that.id = that.checkItemList[that.multipIndex].id;
          that.$postForm(
            "dmc/camera/recordVideoDownload",
            param,
            that.acceptLanguage
          ).then((res) => {
            that.cameraInfo = res.result;
            setTimeout(() => {
              that.initSkyRtc();
            }, 50);
          });
        }else if(that.multipIndex >= size){
          clearInterval(this.timer);
        }else{
          console.log('==========>>>=========while3  ?? ===' + that.multipIndex);
        }
			}, 1000);
    },

    /* 
      修改table tr行的背景色
    */
    tableRowStyle({ row, rowIndex }) {
      // if (row.state == 2) {
      //   return "background-color:#F5F7FA;font-weight: 700;";
      // } else 
      if (rowIndex % 2 == 0) {
        return "background-color: #efefef";
      } else {
        return "background-color: #f9f9f9";
      }
    },
    alarmVideoDownClick(index, row) {
      //dmc/camera/alertVideoDownload
      let param = {
        id: row.id,
      };
      if(!NProgress.isRendered()){
        this.id = row.id;
        NProgress.start();
        this.$postForm(
          "dmc/camera/recordVideoDownload",
          param,
          this.acceptLanguage
        ).then((res) => {
          this.cameraInfo = res.result;
          setTimeout(() => {
            this.initSkyRtc();
          }, 50);
        });
      }
    },
    alarmVideoPlayClick(index, row) {},
    /* 
      修改table header的背景色
    */
    tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return "background-color:#ffffff;color:#000000;font-weight: 700;";
      }
    },
    //查询列表
    getList() {
      if(this.startTime == ''){
        const nowDate = new Date();
        this.endTime = this.getDate(nowDate);
        var startDate = new Date(nowDate.getTime() - 2 * 24 * 60 * 60 * 1000);
        this.startTime =  this.getDate(startDate);
      }
      let param = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        roomId: this.roomId,
        startTime: this.startTime,
        endTime: this.endTime,
      };
      this.$postJson(
        "dmc/cameraRecordVideo/queryListWithPage",
        param,
        this.acceptLanguage
      ).then((res) => {
        this.tableData = res.result.list;
        this.total = Number(res.result.total);
        this.currentPage = res.result.pageNum;
        this.firstPage = res.result.firstPage; //第一页
        this.lastPage = res.result.lastPage; //最后一页
      });
    },
    downloadFinishVideo(){
        let param = {
          id: this.id,
        };
        this.$postForm(
          "dmc/cameraRecordVideo/downloadFinish",
          param,
          this.acceptLanguage
        ).then((res) => {
          setTimeout(() => {
            this.getList();
          }, 50);
        });
    },
    //翻页
    changePage(val) {
      this.pageNum = val;
      this.getList();
    },
    basename(str) {
      var idx = str.lastIndexOf('/')
      idx = idx > -1 ? idx : str.lastIndexOf('\\')
      if (idx < 0) {
        return str
      }
      return str.substring(idx + 1);
    },
    initSkyRtc() {
      // this.cameraInfo
      console.log("============================");
      console.log(this.cameraInfo);
      this.videoSrc = '';
      this.connectmode = this.cameraInfo.conmode;
      this.connectsource = this.cameraInfo.consource;
      this.peerid = this.cameraInfo.toclientid;
      this.CheckedgetUserMedia = true;
      this.StartCalled = false;
      //3.首先下面返回else
      if ( this.wsuri.indexOf(this.cameraInfo.host) != -1 || this.websock != null ) {
        this.sendDisconnect();
        this.handleLeave();
        // 5.上面返回true,新的sessionId和meid,然后用录像的进行ca
        setTimeout(() => {
          this.sessionId = this.newGuid();
          this.websocketonopen();
        }, 2000);
        return;
      } else {
        //4.初始化websocket,然后播放实时视频,然后再点击录像,
        this.sessionId = this.newGuid();
        this.meid = this.newGuid();
        this.initWebSocket();
      }
      var u = window.navigator.userAgent;
      if (u != null) {
        this.isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1; //ios终端
        this.isIos = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        this.isChrome = u.indexOf("Chrome") !== -1; //Chrome 浏览器
        this.isWeixin = u.indexOf("micromessenger") != -1; //微信浏览器
      }
      this.remoteVideo = document.getElementById("remoteVideo");
      console.log(this.remoteVideo);
      if (this.remoteVideo != null) {
        this.remoteVideo.addEventListener("playing", this.OnVideoPlaying);
        this.remoteVideo.addEventListener("play", this.OnVideoPlay);
        this.remoteVideo.addEventListener(
          "loadedmetadata",
          this.OnVideoLoadedMetaData
        );
        this.remoteVideo.addEventListener("canplay", this.OnVideoCanPlay);
        this.remoteVideo.addEventListener("error", this.OnVideoError);
        this.remoteVideo.addEventListener("loadeddata", this.OnVideoLoadedData);
        // this.remoteVideo.addEventListener("pause", function() {
        //     //暂停开始执行的函数
        //     console.log("暂停播放");
        //     this.isVideoPlay = false;
        //   });
        // this.remoteVideo.addEventListener("play", function() {
        //     //暂停开始执行的函数
        //     console.log("继续播放");
        //     this.isVideoPlay = true;
        //   });
        // this.remoteVideo.addEventListener("ended", function() {
        //     //暂停开始执行的函数
        //     console.log("暂停结束");
        //     this.isVideoPlay = false;
        // });
      }
      this.timerstart();
    },
    timerreset() {
      clearTimeout(this.timeoutObj);
      clearTimeout(this.serverTimeoutObj);
    },
    timerstart() {
      var that = this;
      this.serverTimeoutObj = setInterval(function () {
        that.timedelay++;
        if (
          that.websock != null &&
          that.websock &&
          that.websock.readyState === 1
        ) {
          if (that.IsReconnect == true) {
            if (that.RTCPeerConnectionCrea2ted == true) {
              that.handleLeave();
            }
            that.StartCalled = false;
            that.sessionId = that.newGuid();
            that.Connect();
          } else {
            if (that.timedelay > 30) {
              that.timedelay = 0;
              that.sendToServer({
                eventName: "__ping",
                data: {
                  sessionId: that.sessionId,
                  sessionType: "IE",
                  messageId: that.newGuid(),
                  from: that.meid,
                  to: that.peerid,
                },
              });
            }
          }
          that.timerreset();
          that.timerstart();
        } else {
          if (that.IsWebSocketConnecting == false) {
            if (that.websock != null) {
              that.websock.close();
              that.websock = null;
            }
            if (that.RTCPeerConnectionCreated == true) {
              that.handleLeave();
            }
            that.meid = that.newGuid();
            that.initWebSocket();
          } else {
            console.log("IsWebSocketConnecting  ------------------- ");
          }
        }
      }, this.timeout);
    },
    initWebSocket() {
      this.IsWebSocketConnecting = true;
      this.isVideoPlay = true;
      console.log(this.websock);
      if (this.websock != null) {
        console.log("initWebSocket close socket-------");
        this.websock.onmessage = null;
        this.websock.onopen = null;
        this.websock.onerror = null;
        this.websock.onclose = null;
        this.sendDisconnect();
        this.handleLeave();
        this.websock.close();
        this.websock = null;
      }
      
      this.wsuri =
        "wss://" + this.cameraInfo.host + "/wswebclient/" + this.meid;
      // this.wsuri = 'wss://webrtc.qq-kan.com/wswebclient/'+this.meid;
      // this.peerid = "RHZL-00-NYWB-4BNH-00000087";
      //this.sessionId = this.newGuid();
      // this.meid = this.newGuid();
      this.websock = new WebSocket(this.wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen() {
      var that = this;
      this.isVideoPlay = true;
      this.IsWebSocketOpened = true;
      if (this.websock != null && this.websock.readyState === 1) {
        this.StartCalled = false;
        this.Connect();
      } else {
        setTimeout(() => {
          if (that.websock != null && that.websock.readyState === 1) {
            that.StartCalled = false;
            that.Connect();
          }
        }, 100);
      }
    },
    websocketonerror() {
      //连接建立失败重连
      this.IsWebSocketOpened = false;
      this.IsWebSocketConnecting = false;
      this.websock = null;

      this.initWebSocket();
    },
    websocketonmessage(e) {
      //数据接收
      console.log("websocketonmessage:", e.data);
      const data = JSON.parse(e.data);
      switch (data.eventName) {
        case "_create":
          this.handleCreate(data.data);
          break;
        case "_offer":
          this.handleOffer(data.data);
          break;
        case "_answer":
          this.handleAnswer(data.data);
          break;
        case "_ice_candidate":
          this.handleCandidate(data.data);
          break;
        case "_session_disconnected":
          this.handleDisconnect(data.data);
          break;
        case "_post_message":
          this.handlePostMessage(data.data);
          break;
        case "_connectinfo":
          this.handleConnectInfo(data.data);
          break;
        case "_session_failed":
          this.handleSessionFailed(data.data);
          break;
        case "_ping":
          break;
        default:
          console.log("Got default message", data);
          break;
      }
    },
    websocketsend(Data) {
      //数据发送
      if (this.websock != null && this.websock.readyState === 1) {
        this.websock.send(Data);
      }
    },
    websocketclose(e) {
      //关闭
      this.IsWebSocketOpened = false;
      this.IsWebSocketConnecting = false;
      this.websock = null;
      this.handleLeave();
      console.log("断开连接", e);
    },
    NewgetUserMedia(constrains, success, error) {
      //访问用户媒体设备的兼容方法
      console.log("NewgetUserMedia----------------");
      if (
        window.navigator.mediaDevices &&
        window.navigator.mediaDevices.getUserMedia
      ) {
        //最新标准API
        window.navigator.mediaDevices
          .getUserMedia(constrains)
          .then(success)
          .catch(error);
      } else if (window.navigator.webkitGetUserMedia) {
        //webkit内核浏览器
        window.navigator
          .webkitGetUserMedia(constrains)
          .then(success)
          .catch(error);
      } else if (window.navigator.mozGetUserMedia) {
        //Firefox浏览器
        window.navagator.mozGetUserMedia(constrains).then(success).catch(error);
      } else if (window.navigator.getUserMedia) {
        //旧版API
        window.navigator.getUserMedia(constrains).then(success).catch(error);
      } else if (window.navigator.msGetUserMedia) {
        window.navigator.msGetUserMedia(constrains).then(success).catch(error);
      } else {
        this.CheckedgetUserMedia = true;
        this.IsLocalAudioTrack = false;
        console.log("Your browser no getUserMedia function");
      }
    },
    Connect() {
      console.log("Connect Connect Connect");
      this.sendToServer({
        eventName: "__connectto",
        data: {
          sessionId: this.sessionId,
          sessionType: "IE",
          messageId: this.newGuid(),
          from: this.meid,
          to: this.peerid,
        },
      });
    },
    handleDisconnect(data) {
      if (data.sessionId == this.sessionId) {
        console.log("handleDisconnect ", JSON.stringify(data));
        if (this.RTCPeerConnectionCreated == true) {
          this.handleLeave();
          // disconnect
        }
      }
    },
    sendToServer(message) {
      console.log("sendToServer:", message);
      this.websocketsend(JSON.stringify(message));
    },
    PostMessage(message, callback) {
      if (this.connected == true) {
        var messageid = this.newGuid();
        this.messagecallback = callback;
        this.sendToServer({
          eventName: "__post_message",
          data: {
            sessionType: "IE",
            messageId: messageid,
            to: this.peerid,
            from: this.meid,
            message: message,
          },
        });
      }
    },
    handlePostMessage(data) {
      if (this.messagecallback === undefined || this.messagecallback === null) {
        console.log("handlePostMessage");
      } else {
        typeof this.messagecallback === "function" &&
          this.messagecallback(data.message);
        this.messagecallback = null;
      }
    },
    handleSessionFailed(data) {
      console.log("handleSessionFailed ", data);
      if (data.sessionId == this.sessionId) {
        if (this.RTCPeerConnectionCreated == true) {
          this.sendDisconnect();
          this.handleLeave();
        }
        this.sessionId = this.newGuid();
      }
    },
    handleCreate(data) {
      // console.log("WebSocket _create", data);
      if (data.state === "online" || data.state === "sleep") {
        this.IsWebSocketCreateed = true;
        if (
          data.iceServers !== null ||
          data.iceServers !== undefined ||
          data.iceServers !== ""
        ) {
          //console.log("WebSocket iceServers", data.iceServers);
          //服务器把ICE 服务的信息下发到js创建RTCPeerConnection使用
          //configuration = JSON.parse(data.iceServers);
          if (data.iceServers.constructor === Object) {
            console.log(
              " _create  iceServers ---object ---- ",
              JSON.stringify(data.iceServers)
            );
            this.configuration = JSON.parse(JSON.stringify(data.iceServers));
          } else {
            console.log(
              " _create  iceServers ---string ---- :",
              data.iceServers
            );
            this.configuration = JSON.parse(data.iceServers);
          }
        }
        console.log(
          "==========?? =========== StartCalled : " + this.StartCalled
        );
        if (this.StartCalled == false) {
          console.log("handleCreate  start call");
          this.Call();
        }
      } else {
        this.videoFlag = false; //点击了紧急确认按钮  视频码流播放显示 静态图片隐藏
        this.alertPlayFlag = false;
        this.isLivePlay = true; //实时视频播放
        this.isVideoPlay = false; //播放按钮待播放
        this.urgencySureFlag = true; //用于判断实时视频按钮的播放和切换  true--播放   false--停止
        console.log(" _create  offline  ", data.from);
        if(NProgress.isRendered()){
          NProgress.done(true);
        }
        if(this.timer!=null){
          clearInterval(this.timer);
        }
      }
    },
    Call() {
      //console.log("call");
      this.StartCalled = true;
      var audioenable = "false";
      var videoenable = "false";
      var datachannelenable = "true";
      if (this.IsLocalDataChannel == false) {
        datachannelenable = "false";
      }
      if (this.IsLocalAudioTrack == false) {
        audioenable = "recvonly";
      }
      if (this.IsLocalVideoTrack == false) {
        videoenable = "recvonly";
      }
      console.log(
        "call audio ",
        audioenable,
        " video ",
        videoenable,
        " datachannel",
        datachannelenable
      );
      this.sendToServer({
        eventName: "__call",
        data: {
          sessionId: this.sessionId,
          sessionType: "IE",
          messageId: this.newGuid(),
          from: this.meid,
          to: this.peerid,
          mode: this.connectmode,
          source: this.connectsource,
          datachannel: datachannelenable,
          audio: audioenable,
          video: videoenable,
          user: "admin",
          pwd: "123456",
          iceservers: JSON.stringify(this.configuration),
        },
      });
    },
    handleConnectInfo(data) {
      console.log("Got ConnectInfo Message:", data.message);
    },
    handleLeave() {
      var that = this;
      this.videoplayingArc = false;
      console.log("handleLeave  -------------------------------");
      if (this.myDataChannel != null) {
        this.myDataChannel.close();
        this.myDataChannel.onopen = null;
        this.myDataChannel.onclose = null;
        this.myDataChannel.onmessage = null;
        this.myDataChannel.onerror = null;
        this.myDataChannel = null;
      }
      if (this.myPeerConnection != null) {
        console.log(
          "handleLeave  --------signalingState = ",
          this.myPeerConnection.signalingState
        );
        if (this.myPeerConnection.signalingState == "closed") {
          // this.myPeerConnection.getSenders().forEach((sender) => {
          //   console.log("removeTrack  ", sender);
          //   that.myPeerConnection.removeTrack(sender);
          // });
          this.myPeerConnection.close();
          this.handleRelease();
        } else {
          this.myPeerConnection.getSenders().forEach((sender) => {
            console.log("removeTrack  ", sender);
            that.myPeerConnection.removeTrack(sender);
          });
          this.myPeerConnection.close();
          setTimeout(() => {
            if (that.myPeerConnection != null) {
              // if(that.myPeerConnection.signalingState=='closed'){
              that.handleRelease();
              // }
            }
          }, 100);
        }
      }
      // this.isLivePlay = false;
      // this.isVideoPlay = false;
      // this.showPlayLive = true;
      this.videoplaying = false;
      this.RTCPeerConnectionCreated = false;
      this.StartCalled = false;
      this.IceCandidate.splice(0, this.IceCandidate.length);
      // this.videoFlag = false; //点击了紧急确认按钮  视频码流播放显示 静态图片隐藏
      // this.isLivePlay = false; //实时视频播放
      // this.urgencySureFlag = false; //by guo 2020-3-23-15:07添加  用于判断实时视频按钮的播放和切换  true--播放   false--停止
    },
    handleRelease() {
      console.log(
        "handleRelease  ========================================================"
      );
      if (this.myPeerConnection != null) {
        this.myPeerConnection.onicecandidate = null;
        this.myPeerConnection.onaddstream = null;
        this.myPeerConnection.ontrack = null;
        this.myPeerConnection.onsignalingstatechange = null;
        this.myPeerConnection.onicegatheringstatechange = null;
        this.myPeerConnection = null;
      }
      this.IsReconnect = false;
    },
    handleOffer(data) {
      var that = this;
      this.IsReconnect = false;
      console.log("Offer --- ---- sdp  :\n", data.sdp);
      if (this.RTCPeerConnectionCreated == false) {
        this.initPeerConnection();
      }
      if (this.RTCPeerConnectionCreated == false) {
        console.log(
          "handleOffer Failed   RTCPeerConnectionCreated = ",
          this.RTCPeerConnectionCreated
        );
        that.sendDisconnect();
        this.IsReconnect = false;
      }
      try {
        that.myPeerConnection.setRemoteDescription(
          new RTCSessionDescription({ type: "offer", sdp: data.sdp })
        );
      } catch (err) {
        console.log(
          "Error when setRemoteDescription-----------------------------",
          err.message
        );
        that.sendDisconnect();
        this.IsReconnect = false;
      }
      that.myPeerConnection.createAnswer()
        .then(function (answer) {
          that.myPeerConnection.setLocalDescription(answer);
          console.log("Answer sdp :\n" + answer.sdp);
          that.sendToServer({
            eventName: "__answer",
            data: {
              sessionId: that.sessionId,
              sessionType: "IE",
              messageId: that.newGuid(),
              from: that.meid,
              to: that.peerid,
              type: answer.type,
              sdp: answer.sdp,
            },
          });
        })
        .catch(function (error) {
          console.log(
            "Error when create  Answer-----------------------------",
            error.message
          );
          that.sendDisconnect();
          that.IsReconnect = false;
        });
    },
    sendDisconnect() {
      // if(NProgress.isRendered()){
      //   NProgress.done(true);
      // }
      this.sendToServer({
        eventName: "__disconnected",
        data: {
          sessionId: this.sessionId,
          sessionType: "IE",
          messageId: this.newGuid(),
          from: this.meid,
          to: this.peerid,
        },
      });
    },
    handleCandidate(data) {
      var obj = JSON.parse(data.candidate);
      if (
        this.myPeerConnection != null &&
        this.RTCPeerConnectionCreated == true
      ) {
        console.log("candidate --- ----   :", obj.candidate);
        var candidate = new RTCIceCandidate({
          sdpMLineIndex: obj.sdpMLineIndex,
          candidate: obj.candidate,
        });
        this.myPeerConnection.addIceCandidate(candidate);
      } else {
        this.IceCandidate.push(obj);
      }
    },
    initPeerConnection() {
      try {
        console.log('initPeerConnection create PeerConnection configuration =',this.configuration);
        this.myPeerConnection = new RTCPeerConnection(this.configuration);
        console.log('initPeerConnection 2');
        if (this.myPeerConnection != null) {
          if ("addTrack" in this.myPeerConnection) {
            if (this.stream != null) {
              this.stream.getTracks().forEach((track) => {
                this.myPeerConnection.addTrack(track, this.stream);
                if (track.kind === "audio") {
                  track.enabled = this.mute;
                }
              });
            } else {
              console.log("PeerConnection  addTrack  stream is null");
            }
          } else {
            if (this.stream != null) {
              this.myPeerConnection.addStream(this.stream);
              this.stream.getTracks().forEach((track) => {
                //console.log('PeerConnection use addStream type',track.kind);
                if (track.kind === "audio") {
                  track.enabled = this.mute;
                }
              });
            } else {
              console.log("PeerConnection  addStream is null");
            }
          }
          if ("ontrack" in this.myPeerConnection) {
            this.myPeerConnection.ontrack = this.handleRemoteTrackAdded;
          } else {
            this.myPeerConnection.onaddstream = this.handleRemoteStreamAdded;
          }
          this.myPeerConnection.onicecandidate = this.handleIceCandidate;
          this.myPeerConnection.oniceconnectionstatechange =
            this.handleIceConnectionStateChangeEvent;
          this.myPeerConnection.onicegatheringstatechange =
            this.handleIceGatheringStateChangeEvent;
          this.myPeerConnection.onsignalingstatechange =
            this.handleSignalingStateChangeEvent;
          //myPeerConnection.onnegotiationneeded = handleNegotiationNeededEvent;
          // if(this.IsLocalDataChannel == true){
          try {
            this.myDataChannel =
              this.myPeerConnection.createDataChannel("mydatachannel");
            if (this.myDataChannel) {
              this.myDataChannel.onopen = this.handleDataChannelOnOpen;
              this.myDataChannel.onclose = this.handleDataChannelOnClose;
              this.myDataChannel.onmessage = this.handleDataChannelOnMessage;
              this.myDataChannel.onerror = this.handleDataChannelOnError;
            }
          } catch (error) {
            console.log("data_channel_create_error  ");
          }
          // }
          console.log("Sucessed to create PeerConnection");
          this.RTCPeerConnectionCreated = true;
        } else {
          console.log("Failed to create PeerConnection");
          this.RTCPeerConnectionCreated = false;
        }
      } catch (e) {
        console.log("Failed to create PeerConnection, exception: " + e.message);
        this.RTCPeerConnectionCreated = false;
        return;
      }
    },
    getObjectURL(stream) {
      var url = null;
      try {
        if (window.createObjectURL != undefined) {
          url = window.createObjectURL(stream);
          console.log("window createObjectURL", url);
        } else if (window.URL != undefined) {
          url = window.URL.createObjectURL(stream);
          console.log("window window.URLcreateObjectURL ", url);
        } else if (window.webkitURL != undefined) {
          url = window.webkitURL.createObjectURL(stream);
          console.log("window.webkitURL.createObjectURL ", url);
        }
      } catch (error) {
        url = null;
      }
      return url;
    },
    handleRemoteTrackAdded(e) {
      console.log("handleRemoteTrackAdded", e);
      if (this.remoteVideo != null) {
        // console.log("handleRemoteTrackAdded attachStream srcObject stream id = ",e.streams[0].id);
        e.streams[0].getTracks().forEach((track) => {
          console.log("handleRemoteTrackAdded  type", track.kind);
          if (track.kind === "audio") {
            track.enabled = this.speak;
          }
        });
        this.remoteVideo.srcObject = e.streams[0];
        if (this.IsSystemAudioDeviceOK == false) {
          this.remoteVideo.muted = true;
        }
      } else {
        console.log("handleRemoteTrackAdded  video view is null");
      }
    },
    handleRemoteStreamAdded(e) {
      if (this.remoteVideo != null) {
        if ("srcObject" in this.remoteVideo) {
          // console.log("handleRemoteStreamAdded attachStream srcObject stream id = ",e.stream.id);
          this.remoteVideo.srcObject = e.stream;
          e.stream.getTracks().forEach((track) => {
            //console.log('handleRemoteTrackAdded  type',track.kind);
            if (track.kind === "audio") {
              track.enabled = this.speak;
            }
          });
        } else {
          var objUrl = this.getObjectURL(e.stream);
          //console.log("handleRemoteStreamAdded attachStream getObjectURL stream id = ",e.stream.id);
          this.remoteVideo.src = objUrl;
          e.stream.getTracks().forEach((track) => {
            //console.log('handleRemoteTrackAdded  type',track.kind);
            if (track.kind === "audio") {
              track.enabled = this.speak;
            }
          });
        }
      }
    },
    handleIceCandidate(event) {
      if (event.candidate) {
        console.log("onicecandidate: " + event.candidate.candidate);
        this.sendToServer({
          eventName: "__ice_candidate",
          data: {
            sessionId: this.sessionId,
            sessionType: "IE",
            messageId: this.newGuid(),
            to: this.peerid,
            from: this.meid,
            label: event.candidate.sdpMLineIndex,
            candidate: event.candidate.candidate,
          },
        });
      }
    },
    handleIceConnectionStateChangeEvent(event) {
      if (this.myPeerConnection == null) {
        return;
      }
      console.log("*** ICE connection state changed to ", event);
      console.log(
        "*** ICE connection state changed to " +
          this.myPeerConnection.iceConnectionState
      );
      switch (this.myPeerConnection.iceConnectionState) {
        case "closed":
          this.handleRelease();
        case "failed":
        case "disconnected":
          if (this.RTCPeerConnectionCreated == true) {
            this.sendDisconnect();
            this.handleLeave();
          }
          break;
        case "connected":
          this.videoplay();
          break;
      }
    },
    handleIceGatheringStateChangeEvent(event) {
      if (this.myPeerConnection == null) {
        return;
      }
      if (event.target == this.myPeerConnection) {
        console.log(
          "*** ICE gathering state changed to: " +
            event.target.iceGatheringState
        );
      }
      console.log("*** handleIceGatheringStateChangeEvent ", event);
      console.log(
        "*** ICE gathering state changed to: " +
          this.myPeerConnection.iceGatheringState
      );
    },
    handleSignalingStateChangeEvent(event) {
      if (this.myPeerConnection == null) {
        return;
      }
      if (event.target == this.myPeerConnection) {
        console.log(
          "*** WebRTC signaling state changed to: " +
            event.target.signalingState
        );
        switch (this.myPeerConnection.signalingState) {
          case "stable":
            this.videoplay();
            break;
          case "closed":
            this.handleRelease();
            break;
        }
      }
    },
    sendDatachennelMessage(message) {
        if(this.myDataChannel!= null){
            this.myDataChannel.send(JSON.stringify(message));
            console.log(message)
            console.log(JSON.stringify(message))
        }
           
      },
    handleDataChannelOnOpen() {
      console.log("=== ===handleDataChannelOnOpen");
      this.sendDatachennelMessage({
            "eventName": "__download",
            "data": {
              "sessionId": this.sessionId,
              "sessionType": "IE",
              "messageId": this.newGuid(),
              "to": this.peerid,
              "from": this.meid,
              // "message": JSON.stringify({'request':[{'open':this.connectsource}]})
              "message": {
                "request":[{"open":this.connectsource}]
              }
              }
      });
    },
    handleDataChannelOnClose(event) {
      console.log("handleDataChannelOnClose ", event);
    },
    isDataObject(obj){ 
       if(Object.prototype.toString.call(obj) === '[object ArrayBuffer]'){
           return true;   
       } 
      return false;
    },
    handleDataChannelCmdMessage(message) {    
      if(message.response!= null && message.response!=undefined ){
        console.log("Got --------  ", message.response);
        message.response.forEach((val) => {
          if(val.open!= null && val.open!= undefined){
              this.file_data_len =val.open.filesize;
              this.recv_data_len = 0;
              this.incomingFileData = [];
              this.download_start();
          }else if(val.start != null && val.start!= undefined){
            console.log("Got message  ", val.start);
          }else if(val.currentstate!= null && val.currentstate!= undefined){
            console.log("Got message  ", val.currentstate);
          }else if(val.pause != null && val.pause != undefined){
            console.log("Got message  ", val.pause);
          }else if(val.stop  != null && val.stop  != undefined){
            console.log("Got message  ", val.stop);
          }
        })
      }
    },
    download_start() {
        this.sendDatachennelMessage({
          "eventName": "__download",
          "data": {
            "sessionId": this.sessionId,
            "sessionType": "IE",
            "messageId": this.newGuid(),
            "to": this.peerid,
            "from": this.meid,
            "message": {"request":[{"start":0}]}
            }
            });
    },
    download_stop() {
      this.recv_data_len = 0;
        this.sendDatachennelMessage({
          "eventName": "__download",
          "data": {
            "sessionId": this.sessionId,
            "sessionType": "IE",
            "messageId": this.newGuid(),
            "to": this.peerid,
            "from": this.meid,
            "message": {"request":[{"stop":"cancel"}]}
            }
            });
    },
    download_pause() {
        this.sendDatachennelMessage({
          "eventName": "__download",
          "data": {
            "sessionId": this.sessionId,
            "sessionType": "IE",
            "messageId": this.newGuid(),
            "to": this.peerid,
            "from": this.meid,
            "message": {"request":[{"pause":true}]}
            }
            });
    },
    endDownload(){
      var blob = new window.Blob( this.incomingFileData );
      var anchor = document.createElement( 'a' );
      anchor.href = URL.createObjectURL( blob );
      anchor.download =  this.basename(this.connectsource);
      anchor.textContent = '';
      anchor.style.display = 'none';
      if( anchor.click ) {
          anchor.click();
      } else {
          var evt = document.createEvent( 'MouseEvents' );
          evt.initMouseEvent( 'click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null );
          anchor.dispatchEvent( evt );
      }
      this.downloadFinishVideo();
      if(NProgress.isRendered()){
        NProgress.done(true);
      }
    },
    handleDataChannelOnMessage(event) {
      console.log("===handleDataChannelOnMessage===")
      var that = this;
      if(event.type=='message'){
          if(this.isDataObject(event.data)==false){     
            const data = JSON.parse(event.data);
            switch(data.eventName) {
              case "_download":
                this.handleDataChannelCmdMessage(data.data.message);
                break;
              default:
                console.log("Got default message", data);
                break;
            }
          }else{
                var datasliced = new Uint8Array(event.data.slice(0, ));
                console.log(datasliced)
                this.incomingFileData.push(event.data.slice(0, ));
                this.recv_data_len+=datasliced.length;
                if(this.file_data_len>0){
                    var progress = Math.round((this.recv_data_len*100)/this.file_data_len) / 100;
                    console.log(progress)
                    NProgress.set(progress);
                }
                console.log('===recv_data_len: '+this.recv_data_len);
                console.log('===file_data_len: '+this.file_data_len);
                if( this.recv_data_len >= this.file_data_len ) {
                  that.download_stop();
                  that.endDownload();
                }
          }
        }else{
              console.log("handleDataChannelOnMessage",event);
        }
    },
    handleDataChannelOnError(err) {
      console.log("handleDataChannelOnError ", err);
    },
    close() {
      if (this.socketTask && this.socketTask.close) {
        this.socketTask.close();
      }
    },
    newGuid() {
      let s4 = function () {
        return ((65536 * (1 + Math.random())) | 0).toString(16).substring(1);
      };
      return (
        s4() +
        s4() +
        "-" +
        s4() +
        "-4" +
        s4().substr(0, 3) +
        "-" +
        s4() +
        "-" +
        s4() +
        s4() +
        s4()
      ).toUpperCase();
    },
    streamHandler(mystream) {
      this.CheckedgetUserMedia = true;
      window.localStream = mystream;
      this.stream = mystream;
      console.log("streamHandler");
      if ("getTracks" in mystream) {
        //console.log('streamHandler getTracks');
        if (mystream != null) {
          mystream.getTracks().forEach((track) => {
            //console.log('streamHandler getTracks type',track.kind);
            if (track.kind === "audio") {
              this.IsLocalAudioTrack = true;
            } else if (track.kind === "video") {
              this.IsLocalVideoTrack = true;
            }
          });
        }
      }
      if (this.StartCalled == false && this.IsWebSocketCreateed == true) {
        console.log("streamHandler  start call");
        this.Call();
        this.videoFlag = true;
      }
    },
    errorHandler(error) {
      this.CheckedgetUserMedia = true;
      console.log("errorHandler", error);
    },
    videoplay() {
      console.log("videoplay  -------------************-----");
      var that = this;
      if (this.remoteVideo == null) {
        this.remoteVideo = document.getElementById("remoteVideo");
      }
      if (this.videoFlag && this.videoplaying == false) {
        this.videoplaying = true;
        this.videoplayingArc = true;
        console.log("this.remoteVideo.play");
        this.remoteVideo
          .play()
          .then(() => {
            that.videoplaying = true;
            console.log("<video>  play");
            that.isVideoPlay = true;
          })
          .catch((e) => {
            that.videoplaying = false;
            console.log("<video> play error", e.message);
          });
      }
    },
    //用于当视频开始播放的时候。把进度条等等做隐藏
    OnVideoPlaying() {
      console.log("stream is playing-------------");
      this.isVideoPlay = true;
      this.videoShowLoadding = false;
    },
    OnVideoPlay() {
      console.log("<video> event OnVideoPlay------");
    },
    OnVideoLoadedMetaData() {
      console.log("<video> event OnVideoLoadedMetaData----------------");
    },
    OnVideoCanPlay() {
      if (this.remoteVideo != null) {
        console.log(
          "<video>  OnVideoCanPlay-----videoWidth = ",
          this.remoteVideo.videoWidth
        );
        console.log(
          "<video>  OnVideoCanPlay-----videoHeight = ",
          this.remoteVideo.videoHeight
        );
      }
    },
    OnVideoError() {
      console.log("<video> event OnVideoError----------------");
    },
    OnVideoLoadedData() {
      console.log("<video> event OnVideoLoadedData----------------");
    },
    getDate(nowDate) {
      // const nowDate = new Date();
      const date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate(),
      };
      const newmonth = date.month >= 10 ? date.month : "0" + date.month;
      const day = date.date >= 10 ? date.date : "0" + date.date;
      var hours=nowDate.getHours()<10 ? "0"+nowDate.getHours() : nowDate.getHours();
      var minutes=nowDate.getMinutes()<10 ? "0"+nowDate.getMinutes() : nowDate.getMinutes();
      var seconds=nowDate.getSeconds()<10 ? "0"+nowDate.getSeconds() : nowDate.getSeconds();
      return date.year + "-" + newmonth + "-" + day+" "+hours+":"+minutes+":"+seconds;
    },
    queryOlderName(){
      let param = {
        pageNum: 1,
        pageSize: 1,
        oldmanId: this.oldmanId,
      };
      this.$postForm(
        "omc/lifeOldman/queryLifeOldmanWithPage",
        param,
        this.acceptLanguage
      ).then((res) => {
        this.downOldName = "" + res.result.list[0].oldName;
      });
    }
  },
  mounted() {
    this.roomId = sessionStorage.getItem("roomId");
    this.oldmanId = sessionStorage.getItem("oldmanId");
    this.roomNo = sessionStorage.getItem("roomNo");
    if(this.oldmanId == null || this.oldmanId == 'null' || this.oldmanId == '' || 
      this.oldmanId == undefined || this.oldmanId == 'undefined'){
      this.downOldName = '空室'
    }else{
      this.queryOlderName();
    }
    this.getList();
    if(NProgress.isRendered()){
      NProgress.done(true);
    }
  },
  beforeDestroy(){
    console.log('===beforeDestroy====')
    if(NProgress.isRendered()){
      NProgress.done(true);
    }
  },
};
</script>
<style lang="scss" scoped>
.videoDown {
  .border {
    width: 10px;
    height: 30px;
    background: black;
    margin-right: 10px;
  }
  .addBtn {
    color: #7e7e7e;
  }
  .handedness {
    width: 26px;
    height: 26px;
  }
  .hidevideo {
    width: 1px;
    height: 1px;
  }
  .searchBtn {
    background: #409eff;
    color: #ffffff;
  }
  .detailBtn {
    background: #409eff;
    color: #ffffff;
    border-radius: 5px;
  }
  .deleteBtn {
    background: #dddddd;
    color: #010101;
    border-radius: 5px;
  }
  .roomGeneralViewDetail-e {
    width: 80%;
    margin-top: 10px;
  }
  .height40 {
    height: 44px;
    line-height: 44px;
    .height40-span {
      display: inline-block;
      height: 40px;
      line-height: 40px;
      font-size: 18px;
      font-weight: 700;
      img {
        vertical-align: middle;
        margin-right: 15px;
      }
    }
  }

  .btn0 {
    background: #dddddd;
    color: #000000;
  }
}
</style>